/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.channel.io;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 * A command object for asynchronous file access.
 * @author Alex Antonau
 * */
public class IOCommand implements Callable<Integer> {
	public enum Type{
		READ,
		WRITE
	}
	private Type type;
	private FileChannel file;
	
	private long position;
	private ByteBuffer buffer;
	private Future<Integer> future;
	
	public IOCommand(Type type, long position, ByteBuffer buffer) {
		super();
		this.type = type;
		this.position = position;
		this.buffer = buffer;
	}

	public Type getType() {
		return type;
	}
	
	public long getPosition() {
		return position;
	}
	
	public ByteBuffer getBuffer() {
		return buffer;
	}

	public Future<Integer> getFuture() {
		return future;
	}

	void setFuture(Future<Integer> future) {
		this.future = future;
	}

	public java.nio.channels.FileChannel getFile() {
		return file;
	}

	public void setFile(java.nio.channels.FileChannel file) {
		this.file = file;
	}

	@Override
	public Integer call() throws Exception {
		switch (type) {
		case READ:
			return file.read(buffer, position);
		case WRITE:
			return file.write(buffer, position);
		default:
			throw new RuntimeException("Unsupported command type");
		}
	}

}
